import requests
import json
import datetime
import glob

class AccessToken:
    host_cla = 'https://aip.baidubce.com/oauth/2.0/\
token?grant_type=client_credentials&client_id=\
{}&client_secret={}'#获取access_token值的链接

    header = {'Content-Type': 'application/json; charset=UTF-8'}

    def __init__(self,
                 ak = 'IFoOfwGCgoKc6ZMRGGyzyiOH',
                 sk = 'zmPuwDCw8YW9Dvpb6vKTjdVqDk3PaHFZ',
                 img_path = None,
                 img_url = None,
                 face_token = None,
                 img_64 = None,
                 face1 = None,
                 face2 = None,
                 ):
        
        self.ak = ak
        
        self.sk = sk

        self.access_token = self.token_indate()

        if img_path != None:
            img_64 = self.base64_image(img_path)
            self.image,self.image_type = img_64,"BASE64"
        elif img_64 != None:
            self.image,self.image_type = img_64,"BASE64"
            
        elif img_url != None:
            self.image,self.image_type = img_url,"URL"
            
        elif face_token != None:
            self.image,self.image_type = face_token,"FACE_TOKEN"

        elif face1 != None and face2 != None:
            self.image1, self.image2, self.image_type =self.base64_image(face1),self.base64_image(face2),"BASE64"


    def token_indate(self):
        
        '''
        目标：检测token是否有效
              1、保存token,和时间
              2、调用时检测，当前保存的token是否在有效期
              3、如果过期，重新申请一个新的token
        '''
        if glob.glob('access_token.json'):
            with open('access_token.json','r') as f:
                #f.read()
                info_dict = json.load(f)
            if eval(info_dict['expire_time'])>datetime.datetime.now():
                return info_dict['access_token']
            else:

                return self.save_token()        
        else:
            return self.save_token()
        
    def save_token(self):
        access_token = requests.get(
            self.host_cla.format(self.ak,self.sk),
            headers = self.header
            ).json()['access_token']
        
        access_token_dict  = {'access_token':access_token,
                              'expire_time':repr(datetime.datetime.now()+datetime.timedelta(days = 28))
                              }
        
        with open('access_token.json','w') as f:
            f.write(json.dumps(access_token_dict))

        return access_token
        




    #@staticmethod
    def base64_image(self,img_path):
        '''\
        img_path :图片连接
        return :  返回图片的base64编译字符串
        '''
        import base64
        with open(img_path,'rb') as f:
            base64_data = base64.b64encode(f.read())

        return str(base64_data,'utf-8')


    
class AddFace(AccessToken):

    
    def add_face_to_ku(self,
                       user_id,
                       user_info,
                       group_id = "group_repeat",
                       quality_control = "LOW",
                       liveness_control = "LOW",
                       ):

        url = 'https://aip.baidubce.com/rest/2.0/face/v3/\
faceset/user/add?access_token={}'.format(self.access_token)
        

        params = {"image":self.image,
                  "image_type":self.image_type,
                  "group_id":group_id,
                  "user_id":user_id,
                  "user_info":user_info,
                  "quality_control":quality_control,
                  "liveness_control":liveness_control}
        return_info = requests.post(url,
                                    headers = self.header,
                                    data = json.dumps(params),
                                    ).json()
        return return_info

        
class SearchFace(AccessToken):

    def search(self,user_id = None,group_id_list = "1802c"):
        if user_id != None:
            user_id = user_id
        url = 'https://aip.baidubce.com/rest/2.0/face/v3/search?\
access_token={}'.format(self.access_token)
        
        params = {"image":self.image,
                  "image_type":self.image_type,
                  "group_id_list":group_id_list,
                  "quality_control":"LOW",
                  "liveness_control":"NONE"}

        return_info = requests.post(url,
                                    headers = self.header,
                                    data = json.dumps(params),
                                    ).json()
        return return_info
        

class MatchFace(AccessToken):
    def match(self):

        url = 'https://aip.baidubce.com/rest/2.0/face/v3/match?\
access_token={}'.format(self.access_token)

        params = [

         {"image": self.image1,
          "image_type": self.image_type,
          "face_type": "LIVE",
          "quality_control": "LOW"},

         {"image": self.image2,
          "image_type": self.image_type,
          "face_type": "LIVE",
          "quality_control": "LOW"}
         ]

        return_info = requests.post(url,
                                    data = json.dumps(params),
                                    headers = self.header).json()
        print(return_info)
        return return_info

class DetectFace(AccessToken):


    #expression笑脸检测  0不笑，1微笑，2大笑
    #faceshape 脸型置信度。
    #gender 检测性别  male男，female女。
    #glasses 是否带眼镜，0-无眼镜，1-普通眼镜，2-墨镜。
    #landmark  4个关键点位置，左眼中心、右眼中心、鼻尖、嘴中心
    #race  种族 yellow、white、black、arabs。
    #qualities 人脸质量信息

    def detect_face(self):

        url = 'https://aip.baidubce.com/rest/2.0/face/v3/detect?\
access_token={}'.format(self.access_token)
        params = {"image":self.image,
             "image_type":self.image_type,
             "face_field":"faceshape,facetype,beauty,age,glasses,gender"}

        
        return_info = requests.post(url,
                                    data = json.dumps(params),
                                    headers = self.header).json()
        #print(return_info)
        return return_info

    
if __name__ == "__main__":
    
    image_path = 'C:/Users/yangkang/Desktop/3.jpg'
    x = DetectFace(img_path = image_path)
    info = x.detect_face()
    print(info)

    


















